public class Solution892 {
    public int surfaceArea(int[][] grid) {
        int ans=0;
        for (int i=0;i<grid.length;i++){
            for (int j=0;j<grid.length;j++){
                if (i==0){
                    ans+=grid[i][j];
                }else{
                    ans+=Math.max(0,grid[i-1][j]-grid[i][j]);
                }
                if (i==grid.length-1){
                    ans+=grid[i][j];
                }else{
                    ans+=Math.max(0,grid[i+1][j]-grid[i][j]);
                }
                if (j==0){
                    ans+=grid[i][j];
                }else{
                    ans+=Math.max(0,grid[i][j-1]-grid[i][j]);
                }
                if (j==grid.length-1){
                    ans+=grid[i][j];
                }else{
                    ans+=Math.max(0,grid[i][j+1]-grid[i][j]);
                }
                if (grid[i][j]!=0){
                    ans+=2;
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution892().surfaceArea(new int[][]{{1,2},{3,4}}));
    }
}
